package cn.ichiva.tushare.sdk.tushare;

import cn.ichiva.tushare.sdk.common.DataUtils;
import cn.ichiva.tushare.sdk.common.SystemHelper;
import cn.ichiva.tushare.sdk.tushare.entity.TuTable;
import lombok.extern.slf4j.Slf4j;
import org.iq80.leveldb.Options;
import org.iq80.leveldb.impl.DbImpl;
import org.iq80.leveldb.impl.SeekingIteratorAdapter;

import java.io.File;
import java.io.IOException;
import java.util.Optional;

/**
 * 可缓存的数据
 *
 * 使用leveDb进行本地缓存
 */
@Slf4j
public abstract class TuDataCacheAble extends AbstractTuData {

    private static DbImpl db;
    static {
        try {
            db = new DbImpl(new Options(), new File(SystemHelper.getTempDir(),"tushare-cache"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public TuDataCacheAble(TuClient client) {
        super(client);
    }

    /**
     * 取缓存数据
     * @return
     */
    @Override
    public Optional<TuTable> get() {
        byte[] key = getCacheKey();
        byte[] bytes = db.get(key);
        if(bytes != null){
            log.info("命中缓存 key = {}", getRequest().getApi());
            return Optional.of((TuTable)DataUtils.toObject(bytes));
        }

        Optional<TuTable> res = super.get();
        res.ifPresent(e -> db.put(key, DataUtils.toByte(e)));
        return res;
    }

    protected byte[] getCacheKey() {
        return DataUtils.toByte(getRequest());
    }

    /**
     * 清除所有缓存
     */
    public void clearAll(){
        SeekingIteratorAdapter it = db.iterator();
        int n = 0;
        while (it.hasNext()) {
            byte[] key = it.next().getKey();
            db.delete(key);
            n++;
        }

        log.info("清理缓存，影响记录 n = ",n);
    }
}
